/**
 * 
 */
package info.niwota.fwrite;

import org.json.JSONObject;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

/**
 * @author qiangli
 *
 */
public class TextElement extends Element {
	public static final int TYPE_PLAIN = 0;
	public static final int TYPE_EMAIL = 1;
	public static final int TYPE_CHAT = 2;
	public static final int TYPE_PHONE = 3;
	public static final int TYPE_TEXTING = 4;
	public static final int TYPE_URL = 5; //http, file, peer, content, map
	public static final int TYPE_DATE = 6;
	public static final int TYPE_MY_LOCATION = 7; 
	public static final int TYPE_MY_TIME = 8;
	
	private static final long serialVersionUID = 1L;
	
	public static final float DEFAULT_SIZE =  16.0f;
	
	public static final int DEFAULT_COLOR = 0xffffffff;

	private String text;

	private int type = 0;
	
	private float size;
	
	public TextElement(String text) {
		this(TYPE_PLAIN, text, DEFAULT_COLOR, DEFAULT_SIZE);
	}

	public TextElement(int type, String text, int color, float size) {
		this(type, text, text.length()*16, 16, 0, color, size);
	}

	private TextElement(int type, String text, int w, int h, int inset, int color, float size) {
		super(w, h, inset, color);
		this.type = type;
		this.text = text;
		this.size = size;
	}

	public String getText() {
		return text;
	}

	@Override
	public void draw(Canvas canvas, Paint paint, float x, float y,
			float height, float lh) {
		String cs = getText();
		paint.setColor(this.color);
		canvas.drawText(cs, x, y + lh, paint);
	}

	public int getType() {
		return type;
	}

	public float getSize() {
		return size;
	}

	@Override
	public void recompute(Paint paint) {
		final String s = getText();
		Rect bounds = new Rect();
		paint.getTextBounds(s, 0, s.length(), bounds);
		this.width = bounds.width();
		this.height = bounds.height();
	}

	public TextElement(JSONObject obj) throws Exception {
		super(obj);
		
		this.type = obj.getInt(KEY_TYPE);
		this.text = obj.getString(KEY_TEXT);
		this.size = obj.getInt(KEY_SIZE);
	}

	public JSONObject toJSON() throws Exception {
		JSONObject obj = super.toJSON(ELEMENT_TEXT);
		
		obj.put(KEY_TEXT, text);
		obj.put(KEY_TYPE, type);
		obj.put(KEY_SIZE, size);
		
		return obj;
	}
}
